package com.bienvenue.main.httpService;


import com.bienvenue.main.Config;
import com.bienvenue.main.httpService.interceptor.LogInterceptor;
import com.bienvenue.main.httpService.interceptor.TokenHeaderInterceptor;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitClient {
    static RetrofitClient retrofitClient;

    //超时时间
    private static final int DEFAULT_TIMEOUT = 200;
    //缓存时间
    private static final int CACHE_TIMEOUT = 10 * 1024 * 1024;
    private static OkHttpClient okHttpClient;
    private static Retrofit retrofit;

    /**
     * 单例模式，防止接口请求出现OOM
     *
     * @return
     */
    public static RetrofitClient getInstance() {
        if (retrofitClient == null) {
            retrofitClient = new RetrofitClient();
        }
        return retrofitClient;
    }

    public RetrofitClient() {
        okHttpClient = new OkHttpClient.Builder()
//                .cache(cache)
                .addInterceptor(new LogInterceptor())
                .addNetworkInterceptor(new TokenHeaderInterceptor())
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool(8, 15, TimeUnit.SECONDS))
                // 设置同时连接的个数和时间
                .build();
        retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(Config.APP_SERVER_ADDRESS)
                .build();
    }

    public <T> T create(final Class<T> service) {
        if (service == null) {
            throw new RuntimeException("Api service is null!");
        }
        return retrofit.create(service);
    }

    public <T> T execute(Observable<T> observable, Observer<T> subscriber) {
        observable.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);

        return null;
    }

}
